package thread;

import java.util.List;

public class Allocator {

    private List<Object> als;

    /**
     *
     * @param from
     * @param to
     */
    synchronized void apply(Object from, Object to) {
        while (als.contains(from) || als.contains(to)) {
            try {
                // 调用wait方法后，当前线程会被阻塞，进入到互斥锁的等待队列
                // 同事释放互斥锁，其他线程就有机会获得锁,进入临界区A
                als.wait();
            } catch (InterruptedException e) {

            }
            als.add(from);
            als.add(to);
        }
    }

    synchronized void free(Object from, Object to) {
        als.remove(from);
        als.remove(to);
        notifyAll();
    }

}
